function writeTS(TS, fullpath, filename)
% writeTS(TS, fullpath, filename)
% saves TS structure to text file.
% checks and uses appropriate delimiter based on the file extension
%
% example: 
%     writeTS(TS, fullpath)
%     writeTS(TS, directory, filename)
%

if nargin < 2; error('Specify table and file path'); end
if nargin == 2                         
   myFileName = char(fullpath);
else                                   
   myFileName = [char(fullpath) char(filename)];
end

%get the extension to get the delimiter
dotIdx = findstr('.', myFileName);
ext = myFileName(dotIdx(end) + 1:end);
if ext == 'txt'
   delim = ' ';
elseif ext == 'csv'
   delim = ',';
elseif ext == 'prn';
   delim = ' ';
else
   delim = ',';
   warning(['File extension unrecognized in ' myFileName ', using comma as delimiter.']);   
end

fid = fopen(myFileName, 'w');  %previous contents discarded

if fid < 0
   error(strcat('ERROR: Unable to write: ', myFileName));
end

%write header if present
if isfield(TS, 'header');
    if ~isempty(TS.header)
        %get the headers
        if isfield(TS, 'dates');
            if ~isempty(TS.dates)
                if size(TS.header,1) > size(TS.header,2)
                    stringhdr = [{'date'}; (TS.header)]';
                else
                    stringhdr = [{'date'} TS.header];
                end
            end 
        elseif isfield(TS, 'rownames');
             if(~isempty(TS.rownames))
                if size(TS.header,1) > size(TS.header,2)
                    stringhdr = [{'rowname'}; (TS.header)]';
                else
                    stringhdr = [{'rowname'} TS.header];
                end
              end
        else     
             stringhdr = TS.header;
        end 
       
        %add delimiter between each word
        stringhdr(1:end-1) = strcat(stringhdr(1:end-1), delim);
        %print to file
        fprintf(fid, '%s', stringhdr{:});
        fprintf(fid, '\r\n');
    end
end 

%if dates are present set flag variable
foundDates = 0;
foundRownames = 0;
if isfield(TS, 'dates')
    if ~isempty(TS.dates)
        foundDates = 1;
        if length(TS.dates) > size(TS.data, 1)
            warning(['More dates than data for ' myFileName ', truncating extra dates (writeTS.m)']);
            TS.dates = TS.dates(1:size(TS.data, 1));
        elseif length(TS.dates) < size(TS.data, 1)
            error(['More data than dates for ' myFileName]);
        end
     end
elseif isfield(TS, 'rownames')  %if rownames are present set flag variable
    if ~isempty(TS.rownames)
        foundRownames = 1;
        if length(TS.rownames) > size(TS.data, 1)
            warning(['More dates than data for ' myFileName ', truncating extra dates (writeTS.m)']);
            TS.rownames = TS.rownames(1:size(TS.rownames, 1));
        elseif length(TS.rownames) < size(TS.data, 1)
            error(['More data than rownames for ' myFileName]);
        end
    end
end

if foundDates
    format = [['%6.0f' delim] repmat(['%0.9f' delim], 1, size(TS.data, 2) - 1) '%0.9f' '\r\n'];
    fprintf(fid, format, [TS.dates TS.data]');
elseif foundRownames
    format = [repmat(['%0.9f' delim], 1, size(TS.data, 2) - 1) '%0.9f' '\r\n'];
    for i = 1:size(TS.data,1)
      fprintf(fid, ['%s' delim] , TS.rownames{i});
      fprintf(fid, format, [TS.data(i,:)]);
    end
else
    format = [repmat(['%0.9f' delim], 1, size(TS.data, 2) - 1) '%0.9f' '\r\n'];
    fprintf(fid, format, TS.data');
end

fclose(fid);
return
